<template>
  <div
    id="Login-right-box"
    class="right-ipt-box curpoin"
    v-if="!isForGetSuccess"
  >
    <div class="tab-title fexlDf mb20">
      <div
        v-show="!isForGet"
        class="title-item"
        :class="{
          active: (isLoginTitle = index == store.getters.user.loginType),
        }"
        @click="handleLoginTitle(item, index)"
        v-for="(item, index) in loginTitle"
        :key="item.id"
      >
        {{ item.title }}
      </div>

      <div v-show="isForGet" style="width: 100%">
        <div class="forget-title fexlDf f20">
          <el-icon class="curpoin" @click="handleIsForGet">
            <ArrowLeft />
          </el-icon>
          <div>{{ isToBindPhone == 1 ? '绑定手机号' : '重置密码' }}</div>
          <div></div>
        </div>
      </div>
    </div>
    <!-- 登录 -->
    <div class="input-box" v-if="store.getters.user.loginType == 0">
      <el-form
        :model="loginFormData"
        :rules="loginFormrules"
        ref="loginFormRef"
      >
        <el-form-item prop="phone">
          <el-input
            clearable
            class="mb20"
            v-model="loginFormData.phone"
            size="large"
            placeholder="手机/会员卡"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            clearable
            class="mb20"
            v-model="loginFormData.password"
            size="large"
            type="password"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>
      </el-form>
      <p
        @click="hanleForGetPaw"
        class="f12 font-weight500 mb40"
        style="color: #409eff"
        v-show="store.getters.user.loginType == 0"
      >
        忘记密码
      </p>
    </div>
    <!-- 忘记密码 or 注册  or 会员卡登录绑定手机号-->
    <div
      class="input-box"
      v-if="
        store.getters.user.loginType == 2 ||
        store.getters.user.loginType == 1 ||
        isToBindPhone == 1
      "
    >
      <el-form
        ref="forGetFormRef"
        :model="forGetFormData"
        :rules="forGetFormRules"
        class="demo-ruleForm"
      >
        <el-form-item prop="phone">
          <el-input
            clearable
            @input="chanInputValue"
            class="mb20"
            v-model="forGetFormData.phone"
            size="large"
            placeholder="手机号"
          />
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            clearable
            class="mb20"
            v-model="forGetFormData.code"
            size="large"
            placeholder="请输入验证码"
          >
            <template #suffix>
              <el-button
                :disabled="codeInfo.disabled"
                text
                class="curpoin sen-code"
                @click="handleSenCode"
                >{{ codeInfo.codeText }}</el-button
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            clearable
            class="mb20"
            v-model="forGetFormData.password"
            size="large"
            type="password"
            show-password
            placeholder="设置密码，长度6-16个字符"
          />
        </el-form-item>
      </el-form>
    </div>
    <el-button
      :loading="loading"
      @click="handleBtnLogin"
      type="primary"
      class="mb20"
      style="width: 100%"
      size="large"
    >
      <span v-if="loading">{{
        store.getters.user.loginType == 0
          ? '登录中...'
          : store.getters.user.loginType == 1
            ? '注册中...'
            : '提交中...'
      }}</span>
      <span v-else
        >{{
          store.getters.user.loginType == 0
            ? '登录'
            : store.getters.user.loginType == 1
              ? '注册'
              : '提交'
        }}
      </span>
    </el-button>
    <div class="df" v-if="!isForGet">
      <el-tooltip
        class="box-item"
        :visible="tooltipVisible"
        effect="dark"
        content="请阅读并同意协议"
        placement="top"
      >
        <el-checkbox
          @change="handleChange"
          v-model="checked1"
          size="large"
          style="margin-right: 10px"
        />
      </el-tooltip>
      <span class="f12"
        >已阅读并同意
        <span style="color: var(--color-text)" @click="handleUserAgree(1)"
          >《用户协议》</span
        >
        和
        <span style="color: var(--color-text)" @click="handleUserAgree(2)"
          >《隐私政策》</span
        >
      </span>
    </div>

    <div>
      <Vcode :imgs="imgs" :show="isShow" @success="onSuccess" @fail="onFail" />
    </div>

    <div
      style="text-align: center"
      class="f16 font-weight-bold"
      v-if="store.getters.user.loginType == 1"
    >
      已有账号， <span class="go-login" @click="handleLogin">立即登录</span>
    </div>
  </div>

  <!-- 重置密码 -->
  <div v-if="isForGetSuccess" class="right-ipt-box rorget">
    <div class="for-title font-weight-bold">重置密码</div>
    <div class="img-box" style="margin: 60px 0 80px 0">
      <div class="img">
        <img src="@/assets/images/success.png" style="width: 45px" alt="" />
      </div>
      <div class="f12" style="color: var(--color-text)">
        重置成功请牢记新的登录密码
      </div>
    </div>

    <div
      class="f14 font-weight-bold curpoin"
      style="color: #409eff"
      @click="hanleResetLogin"
    >
      重新登录
    </div>
  </div>
</template>

<script setup>
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import Vcode from 'vue3-puzzle-vcode';
import {
  getSendCode,
  getEditPwd,
  getPhoneLogin,
  getMemberLogin,
  getPhoneRegister,
  getMemberBind,
} from '@/api/login';
import bus from '@/utils/bus';
import img01 from '@/assets/images/verification/img01.jpeg';
import img02 from '@/assets/images/verification/img02.jpeg';
import img03 from '@/assets/images/verification/img03.jpeg';
import img04 from '@/assets/images/verification/img04.jpeg';
import img05 from '@/assets/images/verification/img05.jpeg';
import img06 from '@/assets/images/verification/img06.jpeg';
import img07 from '@/assets/images/verification/img07.jpeg';
import img08 from '@/assets/images/verification/img08.jpeg';
import img09 from '@/assets/images/verification/img09.jpeg';
import img10 from '@/assets/images/verification/img10.jpeg';
import img11 from '@/assets/images/verification/img11.jpeg';
import img12 from '@/assets/images/verification/img12.jpeg';
import img13 from '@/assets/images/verification/img13.jpeg';
import img14 from '@/assets/images/verification/img14.jpeg';
const isToBindPhone = ref(-1);
bus.on('isToBindPhone', (data) => {
  isToBindPhone.value = data;
  isForGet.value = false;
});
const loginFormRef = ref('');
const tooltipVisible = ref(false);
const forGetFormRef = ref('');
const store = useStore();
const router = useRouter();
const loading = ref(false);
const checked1 = ref(false);
const isShow = ref(false);
const loginFormData = ref({
  phone: '', //手机号
  member_id: '', //会员卡号
  password: '', //密码
});
const imgs = ref([
  img01,
  img02,
  img03,
  img04,
  img05,
  img06,
  img07,
  img08,
  img09,
  img10,
  img11,
  img12,
  img13,
  img14,
]);
// 验证成功
function onSuccess() {
  isShow.value = false;
  goLogin();
}
// 验证失败
function onFail() {
  ElMessage({
    message: '请重新进行验证！',
    type: 'error',
  });
}

// 验证码or注册
const forGetFormData = ref({
  phone: '',
  code: '',
  password: '',
  isPhome: false,
});
const codeInfo = ref({
  codeText: '发送验证码',
  time: 60,
  disabled: true,
});
const isForGetSuccess = ref(false);
const isForGet = ref(false);
const isLoginTitle = ref(-1);
const loginTitle = ref([
  { id: 1, title: '登录', type: 0 },
  { id: 2, title: '注册', type: 1 },
]);

// 登录规则
const loginFormrules = reactive({
  phone: [{ required: true, message: '请输入手机号或会员卡', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
});
// 重置密码 or 注册规则
const forGetFormRules = reactive({
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
});

const handleChange = (val) => {
  if (val) {
    tooltipVisible.value = false;
  } else {
    tooltipVisible.value = true;
  }
};
const handleLoginTitle = (item) => {
  resetFormData();
  resetRegisterData();
  store.dispatch('user/changeLoginType', item.type);
  isLoginTitle.value = store.getters.user.loginType;
};
// 忘记密码按钮
const hanleForGetPaw = () => {
  store.dispatch('user/changeLoginType', 2);
  isForGet.value = true;
  resetFormData();
  resetRegisterData();
};
const handleIsForGet = () => {
  store.dispatch('user/changeLoginType', 0);
  isForGet.value = false;
  isToBindPhone.value = -1;
};
const handleLogin = () => {
  store.dispatch('user/changeLoginType', 0);
  isLoginTitle.value = 0;
  isForGet.value = false;
};
// 清除登录输入数据
const resetFormData = () => {
  loginFormData.value.isPhome = false;
  loginFormData.value.member_id = '';
  loginFormData.value.phone = '';
  loginFormData.value.password = '';
};
// 清除注册 or 重置密码 输入框数据
const resetRegisterData = () => {
  forGetFormData.value.phone = '';
  forGetFormData.value.code = '';
  forGetFormData.value.password = '';
  forGetFormData.value.isPhome = false;
};
const handleUserAgree = (type) => {
  if (type == 1) {
    window.open('/useragree');
  } else {
    window.open('/privacypolicy');
  }
};
// 会员卡绑定手机号登录
const handleVipBind = () => {
  let newData = {};
  newData.member_id = loginFormData.value.member_id;
  newData.password = loginFormData.value.password;
  newData.loginPassword = forGetFormData.value.password;
  newData.phone = forGetFormData.value.phone;
  newData.code = forGetFormData.value.code;
  fetchMemberBind(newData); //会员卡绑定接口
};
// 登陆方法
const handleBtnLogin = () => {
  // store.getters.user.loginType 0登陆 1注册 2修改密码
  if (store.getters.user.loginType == 0) {
    loginFormRef.value.validate((valid) => {
      if (!valid) return;
      tooltipVisible.value = !checked1.value;
      if (tooltipVisible.value == true) return;
      tooltipVisible.value = valid;
      isShow.value = valid;
      tooltipVisible.value = false;
    });
  } else if (store.getters.user.loginType == 1) {
    forGetFormRef.value.validate((valid) => {
      if (!valid) return;
      tooltipVisible.value = !checked1.value;
      if (!isToBindPhone.value == 1) return;
      fetchPhoneRegister(); //重置密码接口
      store.dispatch('user/changeLoginType', isToBindPhone.value);
    });
  } else if (store.getters.user.loginType == 2) {
    forGetFormRef.value.validate((valid) => {
      // 修改密码接口
      if (valid) {
        if (isToBindPhone.value == 1) {
          handleVipBind();
        } else {
          let newData = {};
          newData.isPhne = forGetFormData.value.isPhome;
          newData.phone = forGetFormData.value.phone;
          newData.password_new = forGetFormData.value.password;
          newData.code = forGetFormData.value.code;
          handleEditPwd(newData);
        }
      } else return;
    });
  }
};
// 通过验证，然后登陆
function goLogin() {
  const isPhome = loginFormData.value.phone.length > 10;
  loginFormData.value.isPhome = isPhome;
  loginFormData.value.member_id = !isPhome ? loginFormData.value.phone : '';
  isPhome ? fetchPhoneLogin() : fetchMemberLogin();
}
// 手机号登录接口
const fetchPhoneLogin = () => {
  loading.value = true;
  getPhoneLogin(loginFormData.value)
    .then((res) => {
      if (res.data.code == 20000) {
        console.log('res:', res);
        handlePortSuccess(res);
        bus.emit('handleCloseLoginCard');
        location.reload();
      } else {
        handlePortError(res);
      }
    })
    .catch(() => {
      loading.value = false;
    });
};
// 会员卡登录接口
const fetchMemberLogin = () => {
  getMemberLogin(loginFormData.value)
    .then((res) => {
      if (res.data.code == 20000) {
        isToBindPhone.value = res.data.data.toBindPhone;
        isForGet.value = true;
        store.dispatch('user/changeLoginType', isToBindPhone.value);
        if (isToBindPhone.value !== 1) {
          bus.emit('handleCloseLoginCard');
          handlePortSuccess(res);
          location.reload();
        }
      } else {
        handlePortError(res);
      }
    })
    .catch(() => {
      loading.value = false;
    });
};
// 会员卡绑定
const fetchMemberBind = (data) => {
  getMemberBind(data)
    .then((res) => {
      if (res.data.code == 20000) {
        handlePortSuccess(res);
        router.push({
          path: '/home',
        });
        location.reload();
        // bus.emit("handleBindVip");
      } else {
        handlePortError(res);
      }
    })
    .catch(() => {
      loading.value = false;
    });
};
// 注册接口
const fetchPhoneRegister = () => {
  getPhoneRegister(forGetFormData.value)
    .then((res) => {
      if (res.data.code == 20000) {
        store.dispatch('user/changeLoginType', 0);
        // router.push("/home");
        location.reload();
        handlePortSuccess(res);
      } else {
        handlePortError(res);
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

// 重置密码
const handleEditPwd = (data) => {
  getEditPwd(data)
    .then((res) => {
      if (res.data.code == 20000) {
        handlePortSuccess(res);
        resetRegisterData();
        isForGetSuccess.value = true;
        codeInfo.value.codeText = '获取验证码';
      } else {
        handlePortError(res);
      }
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

const handlePortError = (res) => {
  ElMessage({
    message: res.data.msg,
    type: 'error',
  });
  loading.value = false;
};
// 重新登录按钮
const hanleResetLogin = () => {
  isForGet.value = false;
  isForGetSuccess.value = false;
  store.dispatch('user/changeLoginType', 0);
};
const handlePortSuccess = (res) => {
  ElMessage({
    message: res.data.msg,
    type: 'success',
  });
  resetFormData();
  loading.value = false;
  // setToken(res.token);
  // store.dispatch("user/changeToken", res.token);
};
const handleSenCode = () => {
  fetchSendCode();
};
// 获取二维码
const fetchSendCode = () => {
  codeInfo.value.disabled = true;
  getSendCode({ phone: forGetFormData.value.phone })
    .then((res) => {
      if (res.data.code == 20000) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
        });
        startCountdown();
      } else {
        codeInfo.value.disabled = false;
        ElMessage({
          message: res.data.msg,
          type: 'error',
        });
        codeInfo.value.disabled = false;
      }
    })
    .catch(() => {
      codeInfo.value.disabled = false;
    });
};
// 倒计时
const startCountdown = () => {
  const restime = codeInfo.value.time--;
  codeInfo.value.codeText = restime + 's后可重发';
  setTimeout(() => {
    if (restime > 0) {
      startCountdown();
    } else {
      codeInfo.value.disabled = false;
      codeInfo.value.codeText = '获取验证码';
      codeInfo.value.time = 60;
    }
  }, 1000);
};
const chanInputValue = (number) => {
  if (number.length > 8) {
    codeInfo.value.disabled = false;
  }
};
</script>

<style lang="scss" scoped>
.right-ipt-box {
  min-width: 320px;

  .tab-title {
    display: flex;
    text-align: center;
    justify-content: space-evenly;

    // justify-content: center;
    .title-item {
      font-size: 20px;
      padding-bottom: 10px;
    }
  }
}

.forget-paw-box {
  width: 320px;
}

.active {
  color: var(--color-text);
  border-bottom: 2px solid var(--color-text);
}

.go-login {
  color: #409eff;
}

.rorget {
  text-align: center;
}

.sen-code {
  color: var(--color-text);
}
</style>
